package com.wlient.basic.Thread.HouseTaskQuene;

import org.junit.Test;

import java.util.concurrent.ArrayBlockingQueue;

public class HouseContractAttachmentProcessor {
    // 任务队列
    private ArrayBlockingQueue<HouseContractFile> blockingQueue;

    // 消费者线程
    private IndexingThread indexingThread;
    public HouseContractAttachmentProcessor() {
        // 容量为200的任务队列
        blockingQueue = new ArrayBlockingQueue<>(200);
        indexingThread = new IndexingThread(blockingQueue);
        // 启动消费者线程
        indexingThread.start();
    }
    /**
     * 处理用户上传电子合同
     * @param houseContractFile 电子合同附件
     */
    @Test
    public void uploadHouseContractAttachment(HouseContractFile houseContractFile) {
        // 提交任务到任务队列
        putTask(houseContractFile);
        // 存储业务数据
        saveBizData(houseContractFile);
        // 存储电子合同附件
        saveAttachmentFile(houseContractFile);

        // 直接返回
        return;
    }
    private void saveBizData(HouseContractFile houseContractFile) {
        System.out.println("==== 存储业务数据完成 ====");
    }
    private void saveAttachmentFile(HouseContractFile houseContractFile) {
        System.out.println("==== 存储合同文件完成 ====");
    }
    private void putTask(HouseContractFile houseContractFile) {
        try {
            blockingQueue.put(houseContractFile);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    static class IndexingThread extends Thread {
        private ArrayBlockingQueue<HouseContractFile> blockingQueue;
        public IndexingThread(ArrayBlockingQueue<HouseContractFile> blockingQueue) {
            this.blockingQueue = blockingQueue;
        }
        @Override
        public void run() {
            try {
                // 死循环，从任务队列中取数据进行处理
                while(true) {
                    HouseContractFile houseContractFile = blockingQueue.take();
                    // 分析附件并生成索引
                    createIndex(houseContractFile);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        private void createIndex(HouseContractFile houseContractFile) {
            try {
                // 耗时2分钟
                Thread.sleep(20000);
                throw new NullPointerException();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("==== 分析附件并生成索引完成 ====");
        }
    }

    public static void main(String[] args) {
        HouseContractAttachmentProcessor houseContractAttachmentProcessor = new HouseContractAttachmentProcessor();
        HouseContractFile houseContractFile =new HouseContractFile();
        houseContractAttachmentProcessor.uploadHouseContractAttachment(houseContractFile);
    }
}